import React, { useEffect, useState, useRef } from 'react';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { ProColumns, EditableProTable } from '@ant-design/pro-table';
import { ExclamationCircleOutlined, RedoOutlined } from '@ant-design/icons';
import { Button, FormInstance, Form } from 'antd';
import { OptType } from '@/utils/constants';
import { isNull, showMsg } from '@/utils/utils';
import GoodName from '@/components/Select/GoodName';
import {
  getGoodsListByPage,
  getCategoryListByPage,
  getBrandListByPage,
  checkBrandExist,
  checkGoodsIsExist,
  updateBrand,
  getSpell,
} from '@/services/stock-goods/api';
interface BrandOptFormProps {
  handleModalVisible: (visible: boolean) => void;
  handleAdd: (value: STOCKGOODSAPI.BrandItem) => Promise<STOCKGOODSAPI.BrandItem>;
  record?: STOCKGOODSAPI.BrandItem;
  optType: string;
  actionRef: any;
}

const OptForm: React.FC<BrandOptFormProps> = (props) => {
  const { handleModalVisible, record = {}, handleAdd, actionRef, optType = OptType.ADD } = props;
  const formRef = useRef<FormInstance>();
  const [editForm] = Form.useForm();
  const actionRef1 = useRef();


  // 表格数据
  const [dataSource, setDataSource] = useState<STOCKGOODSAPI.GoodsItem[]>([]);
  // 修改前品牌名称
  const [beforeEditName] = useState<string>(record.brand_name ?? '');
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  
  // 列配置
  const columns: ProColumns<any>[] = [
    {
      title: '品类',
      dataIndex: 'class_name',
      editable: false,
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      renderFormItem: (form, record1) => {
        return (
          <GoodName
            noStyle
            name1={`goods_name_${record1.recordKey}`}
            allowClear={false}
            scope='B'
            onChange={(e) => {
              // console.log('选中的商品', e, form, record1);
              const obj = {
                class_name: e.class_name,
                goods_id: e.goods_id,
                brand_name: e.brand_name,
                obj: e,
                id: record1.recordKey,
              };
              const result = dataSource.findIndex((item) => item.id === record1.recordKey);
              if (result > -1) {
                dataSource[result] = obj;
                setDataSource(Object.assign([], dataSource));
              }
            }}
          />
        );
      },
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false,
    },
    {
      title: '原归属品牌',
      dataIndex: 'brand_name',
      editable: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        if (record.create_user_id) {
          return [];
        }
        return [
          // <a key="edit" onClick={() => { action?.startEditable?.(record.id)}}>
          //   编辑
          // </a>,
          <a
            key="delete"
            onClick={() => {
              setNewAddNums((prev) => {
                return prev - 1;
              });
              setDataSource(dataSource.filter((item) => item.id !== record.id));
            }}
          >
            删除
          </a>,
        ];
      },
    },
  ];
  // 新增数量
  const [newAddNums, setNewAddNums] = useState<number>(0);
  // 品牌名称检查唯一性
  const onBrandNameChange = async (value: string) => {
    try {
      if (!value) {
        return false;
      }
      const { is_exist } = await checkBrandExist({ brand_name: value });
      return Number(is_exist) === 1;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };
  // 编辑行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 复原
  const onRestore = () => {
    setNewAddNums(0);
    if (optType === OptType.ADD) {
      setDataSource([]);
    } else {
      setDataSource(dataSource.filter((item) => item.create_user_id));
    }
  };

  // 查询商品是否有改动
  const checkChange = (list) => {
    const result = list.filter(item => (item.id).includes('new'));
    setNewAddNums(result.length);
  }

  useEffect(() => {
    if (optType === OptType.EDIT) {
      getGoodsListByPage({
        current: 1,
        pageSize: 10000,
        brand_id: record.brand_id,
      }).then((data: STOCKGOODSAPI.GoodsItemList) => {
        const list = data?.record_list?.map((item) => {
          return {
            ...item,
            id: item.goods_id,
          };
        });
        setDataSource(list || []);
      });
    } else {
      setDataSource([]);
    }
    setNewAddNums(0);
  }, [optType]);

  console.log('dataSource', dataSource);

  return (
    <ModalForm
      className="modal-form"
      width="80%"
      layout="horizontal"
      formRef={formRef}
      modalProps={{
        maskClosable: false,
      }}
      title="新增/编辑品牌"
      visible
      onVisibleChange={handleModalVisible}
      onFinish={async (value: STOCKGOODSAPI.BrandItem) => {
        try {
          // if (editableKeys.length > 0) {
          //   showMsg('您还有未保存的商品信息，请先保存！', MsgType.INFO);
          //   return;
          // }
          const goods_list: STOCKGOODSAPI.GoodsItem[] = dataSource;
          value = Object.assign({}, value);

          if (optType === OptType.ADD) {
            // 新增
            const data = await handleAdd(value);
            // 新增品牌成功
            if (data) {
              const params = {
                addGoodsIds: goods_list.map((item) => item.goods_id),
                brand_name: value.brand_name,
                brand_id: data.brand_id,
              };
              await updateBrand(params);
            }
          } else {
            // 修改
            const params = {
              addGoodsIds: goods_list.map((item) => item.goods_id),
              brand_name: value.brand_name,
              brand_py: value.brand_py,
              brand_id: record.brand_id,
            };
            await updateBrand(params);
          }
          handleModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          showMsg(error?.data?.errmsg);
        }
      }}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '确定',
        },
      }}
    >
      <ProForm.Group>
        <ProFormText
          rules={[
            {
              // validateTrigger: 'onBlur',
              required: true,
              message: '请输入品牌名称',
            },
            {
              // validateTrigger: 'onBlur',
              validator: async (rule, value) => {
                if (
                  optType === OptType.ADD ||
                  (optType === OptType.EDIT && beforeEditName !== value)
                ) {
                  const isExsit = await onBrandNameChange(value);
                  if (isExsit) {
                    return Promise.reject('品牌已存在');
                  }
                  return Promise.resolve();
                }
                return Promise.resolve();
              },
            },
          ]}
          label="品牌名称"
          placeholder="请输入品牌名称"
          width="md"
          name="brand_name"
          validateTrigger="onBlur"
          fieldProps={{
            onBlur: async (e: any) => {
              const value = e.target.value;
              if (value) {
                const { py } = await getSpell(value);
                formRef.current?.setFieldsValue({
                  brand_py: py,
                });
              }
            },
          }}
          initialValue={record.brand_name}
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '请输入检索码',
            },
          ]}
          label="检索码"
          placeholder="请输入检索码"
          width="md"
          name="brand_py"
          initialValue={record.brand_py}
        />
      </ProForm.Group>

      <EditableProTable<STOCKGOODSAPI.GoodsItem>
        rowKey="id"
        rowClassName={(data: STOCKGOODSAPI.GoodsItem) => {
          if (data.id === clickRow){
            return 'tableRowClick';
          }
          if (!isNull(record.brand_id) && (data.id).includes('new')) {
            return 'new-add';
          }
          return '';
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        headerTitle={'调整品牌下商品（可选）'}
        cardBordered
        className={'update-goods-table'}
        actionRef={actionRef1}
        bordered
        value={dataSource}
        onChange={e => {
          checkChange(e);
          setDataSource(e);
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'restore',
                label: (
                  <Button onClick={onRestore} type="primary" icon={<RedoOutlined />}>
                    变更复原
                  </Button>
                ),
              },
            ],
          },
        }}
        toolBarRender={() => [
          <div>
            <span>新增：</span>
            <span style={{ color: '#52C41A' }}>{newAddNums}</span>
            <span style={{ paddingLeft: '20px' }}>总数：</span>
            <span style={{ color: '#2E8DE6' }}>{dataSource.length}</span>
          </div>,
        ]}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          record: () => ({
            id: `new_${Date.now()}`,
          }),
        }}
        // controlled
        editable={{
          form: editForm,
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete];
          },
          onChange: setEditableRowKeys,
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
        }}
        columns={columns}
      />

      <div className="modal-tips">
        <ExclamationCircleOutlined />
        <span>
          编辑品牌和调整品牌商品信息后，请点击下方<strong>确定</strong>按钮保存结果
        </span>
      </div>
    </ModalForm>
  );
};
export default OptForm;
